// 全局语言管理器变量
let languageManager = null;

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成');
    
    // 深色模式切换功能
    initThemeToggle();
    
    // 确保语言管理器可用
    if (typeof LanguageManager !== 'undefined') {
        try {
            // 初始化语言管理器
            languageManager = new LanguageManager();
            
            // 语言选择器事件监听
            const languageSelector = document.getElementById('language-selector');
            if (languageSelector) {
                // 设置当前语言
                const currentLanguage = languageManager.getCurrentLanguage();
                if (currentLanguage) {
                    languageSelector.value = currentLanguage;
                }
                
                languageSelector.addEventListener('change', function() {
                    const selectedLanguage = this.value;
                    languageManager.setLanguage(selectedLanguage);
                });
            }
        } catch (error) {
            console.error('语言管理器初始化失败:', error);
        }
    } else {
        console.error('LanguageManager 未定义');
    }
    
    // 移动端菜单切换
    const hamburger = document.querySelector('.hamburger');
    const navMenu = document.querySelector('.nav-menu');
    
    if (hamburger && navMenu) {
        hamburger.addEventListener('click', function() {
            hamburger.classList.toggle('active');
            navMenu.classList.toggle('active');
        });
        
        // 点击菜单项后关闭移动端菜单
        const navLinks = document.querySelectorAll('.nav-link');
        navLinks.forEach(link => {
            link.addEventListener('click', function() {
                hamburger.classList.remove('active');
                navMenu.classList.remove('active');
            });
        });
    }
    
    // 平滑滚动到指定部分
    function smoothScroll(target) {
        const element = document.querySelector(target);
        if (element) {
            element.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    }
    
    // 为所有导航链接添加平滑滚动
    const navLinks = document.querySelectorAll('a[href^="#"]');
    if (navLinks.length > 0) {
        navLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();
                const target = this.getAttribute('href');
                smoothScroll(target);
            });
        });
    }
    
    // 查看项目按钮点击事件
    const viewProjectsBtn = document.getElementById('view-projects');
    if (viewProjectsBtn) {
        viewProjectsBtn.addEventListener('click', function() {
            smoothScroll('#projects');
        });
    }
    
    // 联系表单提交处理（改进版）
    const contactForm = document.getElementById('contact-form');
    if (contactForm) {
        const nameInput = document.getElementById('name');
        const emailInput = document.getElementById('email-input');
        const messageInput = document.getElementById('message');
        const nameError = document.getElementById('name-error');
        const emailError = document.getElementById('email-error');
        const messageError = document.getElementById('message-error');
        const formSuccess = document.getElementById('form-success');
        const formError = document.getElementById('form-error');
        const submitButton = contactForm.querySelector('.submit-button');
        
        // 实时验证函数
        function validateName() {
            const name = nameInput.value.trim();
            if (name.length < 2) {
                nameError.textContent = '姓名至少需要2个字符';
                nameError.classList.add('show');
                return false;
            } else if (name.length > 50) {
                nameError.textContent = '姓名不能超过50个字符';
                nameError.classList.add('show');
                return false;
            } else {
                nameError.textContent = '';
                nameError.classList.remove('show');
                return true;
            }
        }
        
        function validateEmail() {
            const email = emailInput.value.trim();
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!email) {
                emailError.textContent = '请输入邮箱地址';
                emailError.classList.add('show');
                return false;
            } else if (!emailRegex.test(email)) {
                emailError.textContent = '请输入有效的邮箱地址';
                emailError.classList.add('show');
                return false;
            } else {
                emailError.textContent = '';
                emailError.classList.remove('show');
                return true;
            }
        }
        
        function validateMessage() {
            const message = messageInput.value.trim();
            if (message.length < 10) {
                messageError.textContent = '消息内容至少需要10个字符';
                messageError.classList.add('show');
                return false;
            } else if (message.length > 1000) {
                messageError.textContent = '消息内容不能超过1000个字符';
                messageError.classList.add('show');
                return false;
            } else {
                messageError.textContent = '';
                messageError.classList.remove('show');
                return true;
            }
        }
        
        // 添加实时验证事件监听
        nameInput.addEventListener('blur', validateName);
        nameInput.addEventListener('input', function() {
            if (nameError.textContent) validateName();
        });
        
        emailInput.addEventListener('blur', validateEmail);
        emailInput.addEventListener('input', function() {
            if (emailError.textContent) validateEmail();
        });
        
        messageInput.addEventListener('blur', validateMessage);
        messageInput.addEventListener('input', function() {
            if (messageError.textContent) validateMessage();
        });
        
        // 表单提交处理
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 隐藏之前的消息
            formSuccess.classList.remove('show');
            formError.classList.remove('show');
            
            // 验证所有字段
            const isNameValid = validateName();
            const isEmailValid = validateEmail();
            const isMessageValid = validateMessage();
            
            if (!isNameValid || !isEmailValid || !isMessageValid) {
                formError.classList.add('show');
                return;
            }
            
            // 获取表单数据
            const formData = new FormData(this);
            const name = formData.get('name');
            const email = formData.get('email');
            const message = formData.get('message');
            
            // 显示加载状态
            const originalButtonText = submitButton.textContent;
            submitButton.innerHTML = '<span class="loading-spinner"></span> 发送中...';
            submitButton.disabled = true;
            
            // 模拟异步提交
            setTimeout(() => {
                // 模拟成功提交
                console.log('表单提交数据：', {
                    name: name,
                    email: email,
                    message: message,
                    timestamp: new Date().toISOString()
                });
                
                // 显示成功消息
                formSuccess.classList.add('show');
                
                // 重置表单
                this.reset();
                
                // 恢复按钮状态
                submitButton.textContent = originalButtonText;
                submitButton.disabled = false;
                
                // 3秒后隐藏成功消息
                setTimeout(() => {
                    formSuccess.classList.remove('show');
                }, 3000);
                
            }, 1500); // 模拟1.5秒的提交时间
        });
    }
    
    // 项目卡片点击事件（合并到后面的模态框功能中）
    
    // 导航栏滚动效果 - 智能显示/隐藏
    let lastScrollTop = 0;
    let scrollTimeout;
    const navbar = document.querySelector('.navbar');
    
    if (navbar) {
        window.addEventListener('scroll', function() {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            // 清除之前的定时器
            clearTimeout(scrollTimeout);
            
            // 向下滚动且超过100px时隐藏导航栏
            if (scrollTop > lastScrollTop && scrollTop > 100) {
                navbar.style.transform = 'translateY(-100%)';
                navbar.style.opacity = '0';
            } else {
                // 向上滚动时显示导航栏
                navbar.style.transform = 'translateY(0)';
                navbar.style.opacity = '1';
            }
            
            // 在页面顶部时始终显示
            if (scrollTop <= 50) {
                navbar.style.transform = 'translateY(0)';
                navbar.style.opacity = '1';
            }
            
            // 滚动停止后延迟显示导航栏
            scrollTimeout = setTimeout(() => {
                if (scrollTop > 100) {
                    navbar.style.transform = 'translateY(0)';
                    navbar.style.opacity = '1';
                }
            }, 2000);
            
            lastScrollTop = scrollTop;
            
            // 添加滚动时的背景透明度效果
            if (scrollTop > 50) {
                navbar.style.backgroundColor = 'rgba(44, 62, 80, 0.95)';
            } else {
                navbar.style.backgroundColor = '#2c3e50';
            }
        });
    }
    
    // 技能列表动画效果
    const skillsList = document.querySelector('.skills-list');
    if (skillsList) {
        const skillsItems = skillsList.querySelectorAll('li');
        
        // 为每个技能项添加悬停效果
        skillsItems.forEach((item, index) => {
            item.addEventListener('mouseenter', function() {
                this.style.transform = 'translateX(10px)';
                this.style.backgroundColor = '#3498db';
                this.style.color = 'white';
            });
            
            item.addEventListener('mouseleave', function() {
                this.style.transform = 'translateX(0)';
                this.style.backgroundColor = '#ecf0f1';
                this.style.color = '#2c3e50';
            });
            
            // 添加延迟动画效果
            item.style.animationDelay = `${index * 0.1}s`;
        });
    }
    
    // 图片懒加载（简单的实现）
    const images = document.querySelectorAll('img');
    if (images.length > 0) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.style.opacity = '0';
                    img.style.transition = 'opacity 0.5s ease';
                    
                    // 模拟图片加载
                    setTimeout(() => {
                        img.style.opacity = '1';
                    }, 100);
                    
                    observer.unobserve(img);
                }
            });
        });
        
        images.forEach(img => {
            imageObserver.observe(img);
        });
    }
    
    // 初始化技能进度条动画
    animateSkillBars();
    
    // 添加技能进度条动画
    function animateSkillBars() {
        const skillItems = document.querySelectorAll('.skill-item');
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const skillItem = entry.target;
                    const progressFill = skillItem.querySelector('.progress-fill');
                    const progress = progressFill.getAttribute('data-progress');
                    
                    // 添加in-view类来触发动画
                    skillItem.classList.add('in-view');
                    
                    // 设置CSS变量来控制进度条宽度
                    progressFill.style.setProperty('--progress-width', progress + '%');
                    
                    // 添加数字动画效果
                    const percentageElement = skillItem.querySelector('.skill-percentage');
                    let currentPercentage = 0;
                    const targetPercentage = parseInt(progress);
                    const increment = targetPercentage / 50;
                    
                    const counter = setInterval(() => {
                        currentPercentage += increment;
                        if (currentPercentage >= targetPercentage) {
                            currentPercentage = targetPercentage;
                            clearInterval(counter);
                        }
                        percentageElement.textContent = Math.round(currentPercentage) + '%';
                    }, 30);
                    
                    observer.unobserve(skillItem);
                }
            });
        }, {
            threshold: 0.5,
            rootMargin: '0px 0px -50px 0px'
        });
        
        skillItems.forEach(item => {
            observer.observe(item);
        });
    }
    
    // 添加技能详情提示功能
    const skillItems = document.querySelectorAll('.skill-item');
    if (skillItems.length > 0) {
        skillItems.forEach(item => {
            item.addEventListener('mouseenter', function() {
                const skillName = this.querySelector('.skill-header h4').textContent;
                const percentage = this.querySelector('.skill-percentage').textContent;
                
                // 创建提示元素
                const tooltip = document.createElement('div');
                tooltip.className = 'skill-tooltip';
                tooltip.innerHTML = `
                    <strong>${skillName}</strong><br>
                    熟练度: ${percentage}<br>
                    <small>点击查看详细信息</small>
                `;
                tooltip.style.cssText = `
                    position: absolute;
                    background: rgba(0,0,0,0.8);
                    color: white;
                    padding: 8px 12px;
                    border-radius: 4px;
                    font-size: 12px;
                    z-index: 1000;
                    pointer-events: none;
                    opacity: 0;
                    transition: opacity 0.3s ease;
                    top: -60px;
                    left: 50%;
                    transform: translateX(-50%);
                    white-space: nowrap;
                `;
                
                this.style.position = 'relative';
                this.appendChild(tooltip);
                
                // 显示提示
                setTimeout(() => {
                    tooltip.style.opacity = '1';
                }, 100);
            });
            
            item.addEventListener('mouseleave', function() {
                const tooltip = this.querySelector('.skill-tooltip');
                if (tooltip) {
                    tooltip.style.opacity = '0';
                    setTimeout(() => {
                        tooltip.remove();
                    }, 300);
                }
            });
            
            // 添加点击事件显示详细信息
            item.addEventListener('click', function() {
                const skillName = this.querySelector('.skill-header h4').textContent;
                const percentage = this.querySelector('.skill-percentage').textContent;
                
                // 创建详细信息模态框
                const modal = document.createElement('div');
                modal.className = 'skill-detail-modal';
                modal.innerHTML = `
                    <div class="skill-detail-content">
                        <h3>${skillName} 详细信息</h3>
                        <div class="skill-detail-info">
                            <p><strong>熟练度:</strong> ${percentage}</p>
                            <p><strong>经验年限:</strong> ${getSkillYears(skillName)}</p>
                            <p><strong>主要项目:</strong></p>
                            <ul>
                                ${getSkillProjects(skillName)}
                            </ul>
                            <p><strong>技能描述:</strong></p>
                            <p>${getSkillDescription(skillName)}</p>
                        </div>
                        <button class="close-skill-modal">关闭</button>
                    </div>
                `;
                
                document.body.appendChild(modal);
                
                // 显示模态框
                setTimeout(() => {
                    modal.style.opacity = '1';
                }, 10);
                
                // 关闭事件
                modal.querySelector('.close-skill-modal').addEventListener('click', function() {
                    modal.style.opacity = '0';
                    setTimeout(() => {
                        modal.remove();
                    }, 300);
                });
                
                // 点击外部关闭
                modal.addEventListener('click', function(e) {
                    if (e.target === modal) {
                        modal.style.opacity = '0';
                        setTimeout(() => {
                            modal.remove();
                        }, 300);
                    }
                });
            });
        });
    }
    
    // 技能相关辅助函数
    function getSkillYears(skillName) {
        const years = {
            '前端开发': '5年',
            '后端开发': '4年',
            '数据库设计': '3年',
            'UI/UX设计': '2年',
            '项目管理': '3年'
        };
        return years[skillName] || '2年';
    }
    
    function getSkillProjects(skillName) {
        const projects = {
            '前端开发': '<li>电商网站前端重构</li><li>企业官网响应式改造</li><li>移动端H5活动页面</li>',
            '后端开发': '<li>RESTful API开发</li><li>微服务架构设计</li><li>数据库优化项目</li>',
            '数据库设计': '<li>用户行为分析系统</li><li>数据仓库建设项目</li><li>性能优化项目</li>',
            'UI/UX设计': '<li>移动端应用界面设计</li><li>网站用户体验优化</li><li>品牌视觉系统设计</li>',
            '项目管理': '<li>敏捷开发项目</li><li>跨部门协作项目</li><li>产品迭代管理</li>'
        };
        return projects[skillName] || '<li>相关项目经验</li>';
    }
    
    function getSkillDescription(skillName) {
        const descriptions = {
            '前端开发': '精通HTML5、CSS3、JavaScript，熟练使用React、Vue等现代前端框架，具有丰富的响应式设计和跨浏览器兼容经验。',
            '后端开发': '熟练掌握Node.js、Python等后端技术，具有数据库设计和API开发经验，了解微服务架构和云部署。',
            '数据库设计': '熟悉MySQL、MongoDB等数据库系统，具有数据建模、查询优化和数据仓库建设经验。',
            'UI/UX设计': '了解用户体验设计原则，熟练使用设计工具，能够将用户需求转化为直观的界面设计。',
            '项目管理': '具备敏捷开发管理经验，熟悉项目管理工具和流程，能够有效协调团队资源。'
        };
        return descriptions[skillName] || '具备相关技能和经验。';
    }
    const sections = document.querySelectorAll('section');
    if (sections.length > 0) {
        const sectionObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateY(0)';
                }
            });
        }, {
            threshold: 0.1
        });
        
        sections.forEach(section => {
            section.style.opacity = '0';
            section.style.transform = 'translateY(30px)';
            section.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
            sectionObserver.observe(section);
        });
    }
    
    // 控制台欢迎消息
console.log('%c🚀 欢迎来到我的作品集网站！', 'color: #3498db; font-size: 16px; font-weight: bold;');
console.log('%c💡 这个网站使用了很多现代化的Web技术', 'color: #2ecc71; font-size: 14px;');
console.log('%c🔧 查看源代码了解更多细节', 'color: #e74c3c; font-size: 14px;');

// 控制台彩蛋
console.log('%c🎉 彩蛋时间！', 'color: #f39c12; font-size: 18px; font-weight: bold; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);');
console.log('%c尝试点击技能条，看看会发生什么！', 'color: #9b59b6; font-size: 14px;');
console.log('%c也试试切换语言，所有内容都会自动翻译！', 'color: #1abc9c; font-size: 14px;');

// 创建ASCII艺术
const asciiArt = `
    ██████╗ ██╗  ██╗ █████╗ ███████╗███████╗
    ██╔══██╗██║  ██║██╔══██╗██╔════╝██╔════╝
    ██████╔╝███████║███████║███████╗█████╗  
    ██╔═══╝ ██╔══██║██╔══██║╚════██║██╔══╝  
    ██║     ██║  ██║██║  ██║███████║███████╗
    ╚═╝     ╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝╚══════╝
`;
console.log('%c' + asciiArt, 'color: #3498db; font-family: monospace; font-size: 10px;');
    
    // 页面加载完成后的欢迎提示
    setTimeout(() => {
        // 创建欢迎提示
        const welcomeToast = document.createElement('div');
        welcomeToast.className = 'welcome-toast';
        welcomeToast.innerHTML = `
            <div class="toast-content">
                <h4>🎉 欢迎来到我的作品集！</h4>
                <p>您可以点击技能条查看详细信息，或点击项目卡片了解项目详情。</p>
            </div>
            <button class="toast-close">&times;</button>
        `;
        welcomeToast.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            padding: 15px 20px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
            z-index: 1500;
            max-width: 300px;
            opacity: 0;
            transform: translateX(100%);
            transition: all 0.3s ease;
        `;
        
        document.body.appendChild(welcomeToast);
        
        // 显示动画
        setTimeout(() => {
            welcomeToast.style.opacity = '1';
            welcomeToast.style.transform = 'translateX(0)';
        }, 1000);
        
        // 关闭事件
        welcomeToast.querySelector('.toast-close').addEventListener('click', function() {
            welcomeToast.style.opacity = '0';
            welcomeToast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                welcomeToast.remove();
            }, 300);
        });
        
        // 5秒后自动关闭
        setTimeout(() => {
            if (welcomeToast.parentNode) {
                welcomeToast.style.opacity = '0';
                welcomeToast.style.transform = 'translateX(100%)';
                setTimeout(() => {
                    welcomeToast.remove();
                }, 300);
            }
        }, 5000);
    }, 2000);
    
    // 添加项目详情模态框功能
    const projectCards = document.querySelectorAll('.project-card');
    if (projectCards.length > 0) {
        // 创建模态框
        const modal = document.createElement('div');
        modal.id = 'project-modal';
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <span class="close">&times;</span>
                <div id="modal-content"></div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // 项目详情数据
        const projectDetails = {
            'project1': {
                title: '全栈Web应用',
                description: '这是一个功能完整的全栈Web应用，使用React作为前端框架，Node.js和Express作为后端，MongoDB作为数据库。项目包含用户认证、权限管理、数据可视化等高级功能。',
                technologies: ['React', 'Node.js', 'Express', 'MongoDB', 'JWT', 'Chart.js'],
                features: ['用户注册登录', '角色权限管理', '数据可视化', '响应式设计', 'RESTful API'],
                github: 'https://github.com/example/project1',
                demo: 'https://demo.example.com/project1'
            },
            'project2': {
                title: '响应式企业网站',
                description: '基于Vue.js开发的现代化企业网站，采用组件化设计，支持多语言切换，具有优秀的SEO优化和性能表现。',
                technologies: ['Vue.js', 'Vuex', 'Vue Router', 'Webpack', 'Sass', 'Axios'],
                features: ['单页应用', '多语言支持', 'SEO优化', '性能优化', '移动端适配'],
                github: 'https://github.com/example/project2',
                demo: 'https://demo.example.com/project2'
            },
            'project3': {
                title: '数据分析平台',
                description: 'Python数据分析和机器学习项目，能够处理大规模数据集，提供实时数据分析和预测功能，包含可视化仪表板。',
                technologies: ['Python', 'Pandas', 'Scikit-learn', 'TensorFlow', 'Flask', 'D3.js'],
                features: ['数据清洗', '机器学习', '实时分析', '预测模型', '可视化报告'],
                github: 'https://github.com/example/project3',
                demo: 'https://demo.example.com/project3'
            }
        };
        
        // 为每个项目卡片添加点击事件
        projectCards.forEach(card => {
            const projectId = card.getAttribute('data-project');
            if (projectId && projectDetails[projectId]) {
                card.style.cursor = 'pointer';
                
                card.addEventListener('click', function(e) {
                    if (e.target.classList.contains('project-link')) {
                        return;
                    }
                    
                    e.preventDefault();
                    
                    // 添加点击效果
                    this.style.transform = 'scale(0.98)';
                    setTimeout(() => {
                        this.style.transform = '';
                    }, 150);
                    
                    const details = projectDetails[projectId];
                    const modalContent = document.getElementById('modal-content');
                    
                    modalContent.innerHTML = `
                        <h2>${details.title}</h2>
                        <p>${details.description}</p>
                        
                        <h4>技术栈：</h4>
                        <div class="tech-stack">
                            ${details.technologies.map(tech => `<span class="tech-badge">${tech}</span>`).join('')}
                        </div>
                        
                        <h4>主要功能：</h4>
                        <ul class="feature-list">
                            ${details.features.map(feature => `<li>${feature}</li>`).join('')}
                        </ul>
                        
                        <div class="project-links">
                            <a href="${details.github}" target="_blank" class="btn btn-github">查看代码</a>
                            <a href="${details.demo}" target="_blank" class="btn btn-demo">在线演示</a>
                        </div>
                    `;
                    
                    modal.style.display = 'block';
                    document.body.style.overflow = 'hidden';
                });
            }
        });
        
        // 关闭模态框
        const closeBtn = modal.querySelector('.close');
        closeBtn.addEventListener('click', function() {
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
        });
        
        window.addEventListener('click', function(e) {
            if (e.target === modal) {
                modal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });
        
        // ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.style.display === 'block') {
                modal.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });
    }
});

// 添加一些实用的工具函数
const Utils = {
    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },
    
    // 平滑滚动到顶部
    scrollToTop: function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    }
};

// 添加返回顶部按钮功能
function createBackToTopButton() {
    const button = document.createElement('button');
    button.innerHTML = '↑';
    button.className = 'back-to-top';
    button.style.cssText = `
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background-color: var(--accent-color);
        color: var(--text-light);
        border: none;
        font-size: 20px;
        cursor: pointer;
        opacity: 0;
        transition: opacity 0.3s ease, transform 0.3s ease, background-color 0.3s ease;
        z-index: 999;
        box-shadow: 0 2px 10px var(--shadow-medium);
    `;
    
    document.body.appendChild(button);
    
    // 滚动时显示/隐藏按钮
    window.addEventListener('scroll', Utils.throttle(function() {
        if (window.pageYOffset > 300) {
            button.style.opacity = '1';
            button.style.transform = 'scale(1)';
        } else {
            button.style.opacity = '0';
            button.style.transform = 'scale(0.8)';
        }
    }, 100));
    
    // 点击按钮返回顶部
    button.addEventListener('click', Utils.scrollToTop);
    
    // 按钮悬停效果
    button.addEventListener('mouseenter', function() {
        this.style.backgroundColor = 'var(--accent-hover)';
        this.style.transform = 'scale(1.1)';
    });
    
    button.addEventListener('mouseleave', function() {
        this.style.backgroundColor = 'var(--accent-color)';
        this.style.transform = 'scale(1)';
    });
}

// 页面加载完成后创建返回顶部按钮
document.addEventListener('DOMContentLoaded', createBackToTopButton);

// 深色模式切换功能
function initThemeToggle() {
    const themeToggle = document.getElementById('theme-toggle');
    const html = document.documentElement;
    
    if (!themeToggle) {
        console.warn('深色模式切换按钮未找到');
        return;
    }
    
    // 从localStorage获取保存的主题偏好
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
        html.setAttribute('data-theme', savedTheme);
        updateThemeToggleText(themeToggle, savedTheme);
    } else {
        // 检测系统主题偏好
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        const initialTheme = prefersDark ? 'dark' : 'light';
        html.setAttribute('data-theme', initialTheme);
        updateThemeToggleText(themeToggle, initialTheme);
    }
    
    // 监听系统主题变化
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
        if (!localStorage.getItem('theme')) {
            const newTheme = e.matches ? 'dark' : 'light';
            html.setAttribute('data-theme', newTheme);
            updateThemeToggleText(themeToggle, newTheme);
        }
    });
    
    // 切换按钮点击事件
    themeToggle.addEventListener('click', function() {
        const currentTheme = html.getAttribute('data-theme');
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';
        
        // 添加切换动画效果
        html.style.transition = 'color 0.3s ease, background-color 0.3s ease';
        html.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
        updateThemeToggleText(themeToggle, newTheme);
        
        // 更新语言管理器中的按钮文本
        if (typeof languageManager !== 'undefined' && languageManager) {
            languageManager.updateThemeToggleButton();
        }
        
        // 显示切换提示
        showThemeChangeNotification(newTheme);
        
        // 移除过渡效果，避免影响其他动画
        setTimeout(() => {
            html.style.transition = '';
        }, 300);
    });
    
    // 添加键盘快捷键支持
    document.addEventListener('keydown', function(e) {
        // Ctrl/Cmd + Shift + L 切换主题
        if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'L') {
            e.preventDefault();
            themeToggle.click();
        }
    });
}

// 更新切换按钮文本
function updateThemeToggleText(button, theme) {
    const icon = theme === 'dark' ? '☀️' : '🌙';
    let text;
    
    // 使用语言管理器获取翻译文本
    if (typeof languageManager !== 'undefined' && languageManager) {
        text = theme === 'dark' ? languageManager.getTranslation('light_mode') : languageManager.getTranslation('dark_mode');
    } else {
        // 后备方案
        text = theme === 'dark' ? '浅色模式' : '深色模式';
    }
    
    button.innerHTML = `${icon} ${text}`;
    button.setAttribute('aria-label', `切换到${text}`);
}

// 显示主题切换通知
function showThemeChangeNotification(theme) {
    // 移除现有的通知
    const existingNotification = document.querySelector('.theme-notification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    // 获取翻译文本
    let notificationText;
    if (typeof languageManager !== 'undefined' && languageManager) {
        notificationText = theme === 'dark' ? 
            languageManager.getTranslation('theme_switched_to_dark') : 
            languageManager.getTranslation('theme_switched_to_light');
    } else {
        notificationText = `已切换到${theme === 'dark' ? '深色' : '浅色'}模式`;
    }
    
    // 创建新通知
    const notification = document.createElement('div');
    notification.className = 'theme-notification';
    notification.innerHTML = `
        <div class="notification-content">
            <span class="notification-icon">${theme === 'dark' ? '🌙' : '☀️'}</span>
            <span class="notification-text">${notificationText}</span>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.add('show');
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 2000);
}